<template>
  <div class="data">
    <h2 style="text-align: center">数据源管理</h2>
    <!-- 检索 -->
    <div class="sift">
      <div class="siftitems">
        <span style="margin-right: 10px">系统名称</span>
        <el-input v-model="systemName"></el-input>
      </div>
      <div class="siftitems">
        <span style="margin-right: 10px">数据库类型</span>
        <el-select v-model="value" class="m-2" placeholder="Select">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="siftitems">
        <span style="margin-right: 10px">数据库名</span>
        <el-input v-model="dataBaseName"></el-input>
      </div>
      <div>
        <el-button type="primary" size="'default'" @click="searchDatabaseSource()">查询</el-button>
        <el-button type="info" @click="reset()">重置</el-button>
      </div>
    </div>
    <!-- 分割线 -->
    <hr style="width: 100%; height: 1px; margin-top: 20px" />
    <!-- 弹出按钮，弹出框 -->
    <div class="sifibtn">
      <div style="text-align: center">
        <el-button type="primary" @click="this.showDialog()">添加</el-button>
        <!-- 弹出框 -->
        <el-dialog
          v-model="dialogVisible"
          :title="this.dialogTitle"
          width="750px"
          destroy-on-close
          :show-close="this.addShow"
        >
          <span style="color: red"
            >数据库类型有Mysql,Oracle,SqlServer,PostgreSql</span
          >

          <el-form
            ref="form"
            :inline="true"
            :model="formInline"
            class="form-inline"
            :rules="rules"
            label-position="right"
            label-width="100px"
          >
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="formInline.systemName" clearable @change="this.submitForm()"/>
            </el-form-item>
            <el-form-item label="数据库类型" prop="dataBaseType">
              <el-select v-model="formInline.dataBaseType" clearable>
                <el-option
                  v-for="item in options.slice(0, 4)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="数据库IP" prop="dataBaseIp">
              <el-input v-model="formInline.dataBaseIp" clearable @change="this.submitForm()"/>
            </el-form-item>
            <el-form-item label="数据库名" prop="dataBaseName">
              <el-input 
                v-model="formInline.dataBaseName" 
                @change="this.submitForm()"
              />
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input
                v-model="formInline.userName"
                @change="this.submitForm()"
              />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="formInline.password" type="password" @change="this.submitForm()"/>
            </el-form-item>
            <el-form-item label="端口" prop="port">
              <el-input v-model="formInline.port" @change="this.submitForm()"/>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="formInline.note" @change="this.submitForm()"/>
            </el-form-item>
          </el-form>

          <div v-show="this.addShow" class="from-inline-btn">
            <el-button type="warning" @click="this.testDatabaseSource(formInline)">测试连接</el-button>
            <el-button type="primary" @click="this.addOrigin(formInline)"
              >保存</el-button
            >
          </div>

          <div v-show="this.updateShow" class="from-inline-btn">
            <el-button type="primary" @click="this.save(row)">保存</el-button>
            <el-button type="info" @click="this.dialogVisible = false"
              >取消</el-button
            >
          </div>
        </el-dialog>
      </div>

      <el-button
        style="margin-left: 15px"
        type="danger"
        @click="this.deleteOrigin()"
        >删除</el-button
      >
    </div>
    <!-- 表单 -->
    <div class="table">
      <el-table
        :data="dataFormat()"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column width="40px">
          <template #default="{ row }">
            <el-checkbox v-model="row.isChecked" />
          </template>
        </el-table-column>

        <el-table-column label="id" width="70">
          <template #default="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="系统名称">
          <template #default="{ row }">
            <span @click="updateOrigin(row)" class="highlight">{{
              row.systemName
            }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数据库类型">
          <template #default="{ row }">
            <span>{{ row.dataBaseType }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数据库IP">
          <template #default="{ row }">
            <span>{{ row.dataBaseIp }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数据库名">
          <template #default="{ row }">
            <span>{{ row.dataBaseName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="用户名">
          <template #default="{ row }">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="端口">
          <template #default="{ row }">
            <span>{{ row.port }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        :current-page="page.pageNum"
        :page-size="page.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
/* import { ElMessage } from "element-plus"; */
import request from '@/utils/request';
// import { validate } from "async-validator";
export default {
  name: "OriginPage",
  data() {
    return {
      /* 服务器传来的数据源数据 */
      serverData:[],
      page:{
        pageNum: 1,
        pageSize: 5,
        total: 0,
      },
      //弹窗标题
      dialogTitle: "",
      addShow: false,
      updateShow: false,
      systemName: "",
      dataBaseName: "",
      //下拉框
      value: "",
      options: [
        {
          value: "Mysql",
          label: "Mysql",
        },
        {
          value: "Oracle",
          label: "Oracle",
        },
        {
          value: "SqlServer",
          label: "SqlServer",
        },
        {
          value: "PostgreSql",
          label: "PostgreSql",
        },
      ],
      //表单数据
      /* tableData: [
        {
          id: 0,
          isChecked: false,
          systemName: "manage",
          dataBaseType: "Mysql",
          dataBaseIp: "127.0.0.1",
          dataBaseName: "manage",
          userName: "111",
          port: "8080",
          password: "123",
          note: "",
        },
        {
          id: 1,
          isChecked: false,
          systemName: "manage1",
          dataBaseType: "Oracle",
          dataBaseIp: "127.0.0.1",
          dataBaseName: "manage",
          userName: "111",
          port: "8080",
          password: "123",
          note: "",
        },
        {
          id: 2,
          isChecked: false,
          systemName: "manage2",
          dataBaseType: "SqlServer",
          dataBaseIp: "127.0.0.1",
          dataBaseName: "manage",
          userName: "111",
          port: "8080",
          password: "123",
          note: "",
        },
      ], */
      //消息弹框
      dialogVisible: false,
      formInline: {
        id: null,
        systemName: "",
        dataBaseType: "",
        dataBaseIp: "",
        dataBaseName: "",
        userName: "",
        password: "",
        port: "",
        note: "",
      },
      //表单校验
      form: {
        userName: "",
        systemName: "",
        dataBaseType: "",
        dataBaseIp: "",
        dataBaseName: "",
        password:"",
        port:"",
      },
      //校验规则
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        systemName: [
          { required: true, message: "请输入系统名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "系统名称长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        dataBaseType: [
          { required: true, message: "请选择数据类型", trigger: "change" },

        ],
        dataBaseIp: [
          { required: true, message: "请输入数据库IP", trigger: "blur" },
          {
            pattern:
              /^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/,
            message: "请输入正确的IP地址",
            trigger: "blur",
          },
        ],
        dataBaseName: [
          { required: true, message: "请输入数据库名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "系统名称长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password:[
        { required: true, message: "请输入密码", trigger: "blur" },
        {
          min:6,
          max:16,
          message:"密码长度为6-16位",
          trigger:"blur"
        },
        /* {
          pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{6,16}$/,
          message: '密码必须包含数字、字母、特殊字符', 
          trigger: "blur"
        } */
        ],
        port:[
        { required: true, message: "请输入端口号", trigger: "blur" },
        {
          type:"Number",
          message:"端口号必须为数字",
          trigger:"blur"
        },
        {
          min:1,
          max:5,
          message:"请输入正确的端口号",
          trigger:"blur"
        }
        ]
      },
      //校验结果
      isValidate: null,
    };
  },
  methods: {
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      
      this.searchDatabaseSource()
      
    },
    handleCurrentChange(pageNum) {
      this.page.pageNum = pageNum;

      this.searchDatabaseSource()
    },
    //添加源弹窗
    showDialog() {
      this.clearFrom();
      this.dialogVisible = true;
      this.addShow = true;
      this.updateShow = false;
      this.dialogTitle = "添加数据源";
    },
    //修改数据源
    updateOrigin(data) {
      this.dialogVisible = true;
      this.updateShow = true;
      this.addShow = false;
      this.formInline = Object.assign({}, data);
      this.dialogTitle = "修改数据源";
    },
    //保存修改数据源
    save() {
      if (!this.isValidate) {
        return;
      } else {
        this.editDatabaseSource(this.formInline)
        /* let originData = {};
        originData = this.formInline;
        for (let index = 0; index < this.serverData.length; index++) {
          if (this.serverData[index].id === originData.id) {
            this.serverData[index] = originData;
          }
        }*/
        this.dialogVisible = false; 
      }
    },
    clearFrom() {
      for (let index in this.formInline) {
        this.formInline[index] = "";
      }
    },
    //添加源
    addOrigin(origin) {
      this.dialogVisible = false;
      /* this.submitForm(); */
      if (this.isValidate) {
        this.addDatabaseSource(origin)
      }
    },
    //删除源
    deleteOrigin() {
      this.deleteDatabaseSource()
      /* this.serverData = this.serverData.filter((item) => !item.isChecked);
      ElMessage({
        showClose: true,
        message: "删除成功",
        type: "success",
      }); */
    },
    //表单验证
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // TODO: 提交表单数据
          this.isValidate = true;
          /* ElMessage({
            showClose: true,
            message: "表单验证通过",
            type: "success",
          }); */
        } else {
          this.isValidate = false;
          /* ElMessage({
            showClose: true,
            message: "表单验证失败",
            type: "error",
          }); */
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    /* 获取所有的数据源 */
    getAllSource(){
      let searchByDataSource = {
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
      }

      request.get("newapi/data/search/datasource",{
        params: searchByDataSource
      }).then(
        res => { 
          if(res.code == 200){
            console.log(res.data);

            if(res.data == null || res.length == 0){
              this.serverData = []
              this.page.total = 0
            }
            else{
              this.serverData = res.data
              this.page.total = res.total
              this.dataFormat()
            }
            /* this.page.pageNum = 1 */
          }else{
            this.$message({
              message: "操作失败!",
              type: 'error'
            }) 
          }
        },
        error => { 
          this.$message({
            message: error.message,
            type: 'error'
          }) 
        },
      )

      /* request.get('/newapi/data/getAllSource').then(
        res => {
          this.serverData = res.data
          this.dataFormat()
          this.page.total = this.serverData.length
        },
        error => {console.log(error);}
      ) */
    },
    /* 修改数据格式 */
    dataFormat(){
      this.serverData.forEach(element => {
        if(element != undefined && element != null){
          element.isChecked = false
          element.dataBaseType = element.dbType
          element.dataBaseIp = element.dbIp
          element.dataBaseName = element.dbName
          element.port = element.dbPort
          element.note = element.dbInfo
        }
        
      });
      return this.serverData
    },
    /* 添加数据源 */
    addDatabaseSource(origin){
      let params = {
        dbInfo: origin.note,
        dbIp: origin.dataBaseIp,
        dbName: origin.dataBaseName,
        dbPort: origin.port,
        dbType: origin.dataBaseType,
        id: origin.id,
        password: origin.password,
        systemName: origin.systemName,
        userName: origin.userName
      }
      console.log(params);
      request.post('/newapi/data/add/datasource', params).then(
        res => {
          if(res.code == 200){
            this.$message({
              message:'操作成功！',
              type:'success'
            })
            console.log(res);
            this.getAllSource()
          }
        },
        error => {
          console.log(error.message);
          this.$message({
            message:'操作失败！',
            type:'success'
          })
        }
      )
    },
    /* 修改数据源 */
    editDatabaseSource(origin){
      let params = {
        dbInfo: origin.note,
        dbIp: origin.dataBaseIp,
        dbName: origin.dataBaseName,
        dbPort: origin.port,
        dbType: origin.dataBaseType,
        id: origin.id,
        password: origin.password,
        systemName: origin.systemName,
        userName: origin.userName
      }
      console.log(params);
      request.post('/newapi/data/edit/datasource', params).then(
        res => {
          if(res.code == 200){
            this.$message({
              message:'操作成功！',
              type:'success'
            })
            console.log(res);
            this.getAllSource()
          }else{
            this.$message({
              message:res.msg,
              type:'error'
            })
          }
        },
        error => {
          console.log(error.message);
          this.$message({
            message:error.message,
            type:'error'
          })
        }
      )
    },
    /* 测试连接数据源 */
    testDatabaseSource(origin){
      if(!this.isValidate){
        this.$message({
          message:'请填写正确的数据库信息！',
          type: 'error'
        })
        return
      }

      let params = {
        dbInfo: origin.note,
        dbIp: origin.dataBaseIp,
        dbName: origin.dataBaseName,
        dbPort: origin.port,
        dbType: origin.dataBaseType,
        id: origin.id,
        password: origin.password,
        systemName: origin.systemName,
        userName: origin.userName
      }
      console.log(params);
      request.post('/newapi/data/testConn', params).then(
        res => {
          if(res.code == 200){
            this.$message({
              message:'数据库测试连接成功！',
              type:'success'
            })
          }else{
            this.$message({
              message:'数据库测试连接失败！',
              type:'error'
            })
          }
        },
        error => {
          console.log(error.message);
          this.$message({
            message:'数据库测试连接失败！',
            type:'error'
          })
        }
      )
    },
    /* 批量删除数据源 */
    deleteDatabaseSource(){
      let deleteList = []
      this.serverData.forEach(element => {
        if(element.isChecked){
          deleteList.push(element.id)
        }
      });
      
      if(deleteList.length == 0){
        this.$message({
          message:'请选择要删除的数据源！',
          type: 'error'
        })
        return
      }
      console.log({deleteList});
      request.post("/newapi/data/delete/datasource",deleteList).then(
        res => { 
          if(res.code == 200){
            console.log(res.data);
            this.$message({
              message: "操作成功",
              type: 'success'
            })
            this.getAllSource()
          }else{
            this.$message({
              message: "操作失败!",
              type: 'error'
            }) 
          }
        },
        error => { 
          this.$message({
            message: error.message,
            type: 'error'
          }) 
        },
      )
    },
    /* 搜索数据源 */
    searchDatabaseSource(){
      let searchByDataSource = {
        dbName : this.dataBaseName,
        systemName : this.systemName,
        dbType : this.value,
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize,
      }

      request.get("newapi/data/search/datasource",{
        params: searchByDataSource
      }).then(
        res => { 
          if(res.code == 200){
            console.log(res.data);
            this.$message({
              message: "操作成功",
              type: 'success'
            })
            if(res.data == null || res.length == 0){
              this.serverData = []
              this.page.total = 0
            }
            else{
              this.serverData = res.data
              this.page.total = res.total
              this.dataFormat()
            }
            /* this.page.pageNum = 1 */
          }else{
            this.$message({
              message: "操作失败!",
              type: 'error'
            }) 
          }
        },
        error => { 
          this.$message({
            message: error.message,
            type: 'error'
          }) 
        },
      )
    },
    /* 重置 */
    reset(){
      this.dataBaseName = ''
      this.systemName = ''
      this.value = ''
      this.getAllSource()
      this.page.pageNum = 1
    }
  },
  mounted(){
    this.getAllSource()
  },
};
</script>

<style scoped>
.data {
  display: flex;
  flex-direction: column;
  width: 100%;

  .sift {
    width: 100%;
    display: flex;
    justify-content: space-around;
    padding-top: 20px;
  }
}
.siftitems {
  display: flex;
  flex-direction: row;
}
span {
  white-space: nowrap;
}
.sifibtn {
  margin-top: 10px;
  display: flex;
  flex-direction: row;
}
.table {
  width: 100%;
  margin-top: 20px;
}
.form-inline {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 10px;
  align-items: center;
}

.from-inline-btn {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.highlight {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
.demo-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
